package com.hg.concurent.demo5;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * created by skh on 2019/12/21
 */
public class Run2Demo {

	//5名选手,必选所有先到起点准备后,再同时开跑,最后所有人到达终点后,比赛结束
	public static void main(String[] args) {
		CyclicBarrier startBarrier = new CyclicBarrier(3, new Runnable() {
			@Override
			public void run() {
				System.out.println("所有队员准备完毕");
			}
		});
		CyclicBarrier endBarrier = new CyclicBarrier(3, new Runnable() {
			@Override
			public void run() {
				System.out.println("所有队员到达终点,比赛结束");
			}
		});

		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName() + "开始准备");
				ThreadUtil.sleep(RandomUtil.randomInt(1000, 3000));
				System.out.println(Thread.currentThread().getName() + "准备完毕");

				try {
					startBarrier.await();
				} catch (Exception e) {
				}
				System.out.println(Thread.currentThread().getName() + "开始奔跑");
				ThreadUtil.sleep(RandomUtil.randomInt(1000, 3000));
				System.out.println(Thread.currentThread().getName() + "到达终点");
				try {
					endBarrier.await();
				} catch (Exception e) {
				}
			}
		}, "A").start();

		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName() + "开始准备");
				ThreadUtil.sleep(RandomUtil.randomInt(1000, 3000));
				System.out.println(Thread.currentThread().getName() + "准备完毕");
				try {
					startBarrier.await();
				} catch (Exception e) {
				}
				System.out.println(Thread.currentThread().getName() + "开始奔跑");
				ThreadUtil.sleep(RandomUtil.randomInt(1000, 3000));
				System.out.println(Thread.currentThread().getName() + "到达终点");
				try {
					endBarrier.await();
				} catch (Exception e) {
				}
			}
		}, "B").start();

		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName() + "开始准备");
				ThreadUtil.sleep(RandomUtil.randomInt(1000, 3000));
				System.out.println(Thread.currentThread().getName() + "准备完毕");
				try {
					startBarrier.await();
				} catch (Exception e) {
				}
				System.out.println(Thread.currentThread().getName() + "开始奔跑");
				ThreadUtil.sleep(RandomUtil.randomInt(1000, 3000));
				System.out.println(Thread.currentThread().getName() + "到达终点");
				try {
					endBarrier.await();
				} catch (Exception e) {
				}
			}
		}, "C").start();
	}
}
